

#include "jsontest.h"
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <string>


bool TestJson::Show(json_t* value,int deep)
{
    if(json_is_object(value))
    {
        printf("\tobject \n");
        get_object(value,++deep);
    }
    if(json_is_array(value))
    {
        printf("\tarrry \n");
        for(int i = 0; i< json_array_size(value); i++)
        {
            int deeps = deep;
            json_t *obj = json_array_get(value, i);
            get_object(obj,++deeps); 
            printf("\n");
        }

    }
    if(json_is_string(value))
    {
        printf("\tstring value :%s", json_string_value(value));
    }
    if(json_is_integer(value)) 
    {
        printf("\tint value :%d", json_integer_value(value));  
    }
    if(json_is_number(value)) 
    {
        printf("\tfloat value :%f", json_number_value(value));
    }
    if(json_is_boolean(value)) 
    {
        printf("\tbool value :%s", json_is_true(value)?"true":"false");
    }
    printf("\n");
    return true;
}
void TestJson::get_object(json_t *object,int deep)
{
    void *iter = json_object_iter(object);
    int i = 0;
    while(1)
    {
        for(int j = 0;j <deep;j++)
        {
            printf("\t");
        }
        printf("key [%d]=%s", i,json_object_iter_key(iter));
        json_t *iter_values = json_object_iter_value(iter);
        Show(iter_values,deep);
        if((iter = json_object_iter_next(object, iter)) == NULL) 
        {
            break;
        }
        i++;
    }
}

void TestJson::Test()
{
    json_error_t error;
    std::string buf;
    std::ifstream infile;
    infile.open("redad");
    std::getline(infile,buf);
    std::string newbuf = std::string("{\"obj\": ") + buf + std::string("}");
    printf("buf=%s\n",newbuf.c_str());
//    json_t* root = json_load_file ("redad", JSON_ENSURE_ASCII | JSON_ENCODE_ANY, &error);
    json_t* root = json_loads(newbuf.c_str(),JSON_ENCODE_ANY, &error); 
    json_t* obj = json_object_get( root, "obj" );
    if(!json_is_string(obj)) 
    {
        return;
    }
    printf("%s\n",json_string_value(obj));
    json_t* root1 = json_loads(json_string_value(obj) ,JSON_ENCODE_ANY, &error); 
    char *result;
    result = json_dumps(root1, JSON_PRESERVE_ORDER);
    int rc = json_dump_file(root1, "./test.json", 0);
    if(rc)
    {
        printf("cannot save json to file\n");
    }
    printf("result=%s json_error_t=%s\n", result,error.text);
    get_object(root1);
}
